import traceback
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QTableWidget, QTableWidgetItem, QHBoxLayout, QGridLayout
from PyQt5.QtCore import Qt
import platform
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import os
import sys

# 配置matplotlib中文字体
if platform.system() == 'Darwin':  # macOS
    matplotlib.rcParams['font.family'] = ['Hiragino Sans GB', 'Apple LiGothic Medium', '.AppleSystemUIFont']
else:  # Windows 和 Linux
    matplotlib.rcParams['font.family'] = ['SimHei', 'Microsoft YaHei', 'WenQuanYi Micro Hei']

matplotlib.rcParams['axes.unicode_minus'] = False
matplotlib.rcParams['font.size'] = 9

def get_resource_path(relative_path):
    """获取资源文件的绝对路径"""
    try:
        # PyInstaller创建临时文件夹,将路径存储在_MEIPASS中
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

def format_hex_with_space(number: int) -> str:
    """
    将整数格式化为去掉0x前缀、每两位一个空格的十六进制字符串（8位，不足补零）。
    例如：0x1234ABCD -> '12 34 AB CD'
    """
    hex_str = f"{number:08X}"
    return ' '.join([hex_str[i:i+2] for i in range(0, 8, 2)])

def format_vc_frame_count(number: int) -> str:
    """
    将虚拟信道帧计数格式化为去掉0x前缀、每两位一个空格的十六进制字符串（6位，不足补零）。
    虚拟信道帧计数为3字节（24位）
    例如：0x03B64F -> '03 B6 4F'
    """
    hex_str = f"{number:06X}"
    return ' '.join([hex_str[i:i+2] for i in range(0, 6, 2)])